<template>
  <div class="music-player-container">
    <!-- 歌曲信息展示 -->

    <!-- 播放器控制部分 -->
    <div class="audio-player">
      <div class="music-info">
        <div class="album-art" :class="{ rotating: playStatus }">
          <img :src="picture" alt="album cover" />
        </div>
      </div>
      <div class="song-details">
        <h2 class="song-title">{{ sing }}</h2>
        <p class="artist">{{ wenan }}</p>
      </div>
      <!-- 时间进度 -->
      <span class="play-time">{{ transTime(audioCurrent) }}</span>

      <!-- 进度条
      <div class="play-progress" @click="seekAudio">
        <div class="play-current-progress" :style="{ width: `${playProgress}%` }"></div>
      </div> -->
      <!-- 修改后的进度条模板 -->
      <div ref="progressBar" class="play-progress" @click="seekAudio">
        <div class="play-current-progress" :style="{ width: `${playProgress}%` }"></div>
      </div>
      <span class="play-time">{{ transTime(audioDuration) }}</span>

      <!-- 播放/暂停按钮 -->
      <img
        :src="playStatus ? stopIcon : startIcon"
        alt="play/pause"
        class="play-icon"
        @click="togglePlay"
      />

      <!-- 音量控制 -->
      <div class="volume-control">
        <img
          :src="audioVolume > 0 ? volumeIcon : muteIcon"
          alt="volume"
          class="play-voice"
          @click="toggleMute"
        />
        <el-slider
          v-model="audioVolume"
          :min="0"
          :max="1"
          :step="0.01"
          :show-tooltip="false"
          @input="onVolumeChange"
        />
        <!-- <input
          v-model="audioVolume"
          type="range"
          min="0"
          max="1"
          step="0.1"
          @input="onVolumeChange"
        /> -->
        <span style="display: inline-block; width: 30px">{{ parseInt(audioVolume * 100) }}%</span>
      </div>

      <!-- 播放速度控制 -->
      <!-- <el-popover v-model:visible="speedVisible" placement="top" :width="80">
        <div class="speed-options">
          <div
            v-for="item in speedList"
            :key="item.value"
            class="speed-option"
            :class="{ active: activeSpeed === item.value }"
            @click="onChangeSpeed(item.value)"
          >
            {{ item.label }}
          </div>
        </div>
        <template #reference>
          <span class="play-speed" @click="onHandleSpeed">{{ activeSpeed }}x</span>
        </template>
      </el-popover> -->

      <!-- 隐藏的audio元素 -->
      <audio
        ref="audioRef"
        :src="musicSource"
        @canplay="onCanplay"
        @timeupdate="updateProgress"
      ></audio>
    </div>

    <!-- 加载状态 -->
    <!-- <van-loading v-if="loading" class="loading" /> -->

    <!-- 错误提示 -->
    <!-- <van-empty v-if="error" description="加载失败，请稍后再试" /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from "vue";
import axios from "axios";
// import startIcon from "@/assets/image/start.png";
// import stopIcon from "@/assets/image/stop.png";
// import volumeIcon from "@/assets/image/bofang.png";
// import muteIcon from "@/assets/image/jingy.png";
import stopIcon from "@/assets/live/music/skip-back-mini-fill.png";
import startIcon from "@/assets/live/music/play-circle-fill.png";
import volumeIcon from "@/assets/live/music/sound.png";
import muteIcon from "@/assets/live/music/sound.png";

// 响应式数据
const musicSource = ref("");
const wenan = ref("佳佳");
const sing = ref("真的爱上你");
const picture = ref("");
const loading = ref(true);
const error = ref(false);

// const speedVisible = ref(false);
const audioRef = ref<HTMLAudioElement>();
const activeSpeed = ref(1);
const audioDuration = ref(0);
const audioCurrent = ref(0);
const audioVolume = ref(1);
const playStatus = ref(false);
const playProgress = ref(0);
const timeInterval = ref<number>();
const progressBar = ref<HTMLElement>(); // 新增进度条容器引用

// const speedList = [
//   { label: "2.0x", value: 2 },
//   { label: "1.5x", value: 1.5 },
//   { label: "正常", value: 1 },
//   { label: "0.75x", value: 0.75 },
// ];

// 方法
const togglePlay = async () => {
  if (playStatus.value) {
    onPause();
  } else {
    await onPlay();
  }
};

const onPlay = async () => {
  if (playProgress.value === 100) {
    audioRef.value!.currentTime = 0;
  }
  try {
    await audioRef.value!.play();
    playStatus.value = true;
    startProgressTracking();
  } catch (err) {
    console.error("播放失败:", err);
  }
};

// const onPause = () => {
//   audioRef.value!.pause();
//   playStatus.value = false;
//   clearInterval(timeInterval.value);
// };

const startProgressTracking = () => {
  timeInterval.value = setInterval(() => {
    audioCurrent.value = audioRef.value!.currentTime;
    audioDuration.value = audioRef.value!.duration;

    playProgress.value = (audioCurrent.value / audioDuration.value) * 100;
    if (playProgress.value === 100) onPause();
  }, 100);
};

// const seekAudio = (e: MouseEvent) => {
//   const rect = (e.target as HTMLElement).getBoundingClientRect();
//   const seekPosition = (e.clientX - rect.left) / rect.width;
//   audioRef.value!.currentTime = audioDuration.value * seekPosition;
// };
const seekAudio = (e: MouseEvent) => {
  if (!progressBar.value || !audioRef.value) return;

  // 获取容器尺寸
  const rect = progressBar.value.getBoundingClientRect();

  // 计算点击位置占比（限制在0-1之间）
  const clickPosition = Math.min(Math.max(0, e.clientX - rect.left), rect.width);
  const seekPercentage = clickPosition / rect.width;

  // 设置播放时间（确保有有效时长）
  if (audioDuration.value > 0) {
    audioRef.value.currentTime = audioDuration.value * seekPercentage;
  }
};

const toggleMute = () => {
  audioVolume.value = audioVolume.value > 0 ? 0 : 1;
  audioRef.value!.volume = audioVolume.value;
};

const onVolumeChange = (val) => {
  console.log(val, "eeee");
  audioVolume.value = val;
  // const target = e.target as HTMLInputElement;
  audioRef.value!.volume = val;
  // console.log(audioRef.value!.volume, "audioRef.value!.volume");
};
const transTime = (value: number) => {
  const totalSeconds = Math.floor(value);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  const pad = (num: number) => num.toString().padStart(2, "0");

  return hours > 0
    ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
    : `${pad(minutes)}:${pad(seconds)}`;
};
// 其他方法保持原有逻辑...
// const transTime = (value: number) => {
//   let time = "";
//   let h = parseInt(String(value / 3600));
//   value %= 3600;
//   let m = parseInt(String(value / 60));
//   let s = parseInt(String(value % 60));
//   if (h > 0) {
//     time = formatTime(h + ":" + m + ":" + s);
//   } else {
//     time = formatTime(m + ":" + s);
//   }
//   return time;
// };

// const formatTime = (value: string) => {
//   let time = "";
//   let s = value.split(":");
//   let i = 0;
//   for (; i < s.length - 1; i++) {
//     time += s[i].length == 1 ? "0" + s[i] : s[i];
//     time += ":";
//   }
//   time += s[i].length == 1 ? "0" + s[i] : s[i];
//   return time;
// };
// const onSetVolume = (value: number) => {
//   audioRef.value.volume = value;
//   audioVolume.value = value;
// };
// const onPlay = async () => {
//   if (playProgress.value === 100) audioRef.value.currentTime = 0;
//   await audioRef.value.play();
//   playStatus.value = true;
//   audioDuration.value = audioRef.value.duration;

//   timeInterval.value = setInterval(() => {
//     audioCurrent.value = audioRef.value.currentTime;
//     playProgress.value = (audioCurrent.value / audioDuration.value) * 100;
//     if (playProgress.value === 100) onPause();
//   }, 100);
// };

const onPause = () => {
  audioRef.value.pause();
  playStatus.value = false;
  clearInterval(timeInterval.value);
};

onBeforeMount(() => {
  clearInterval(timeInterval.value);
});

// const speedList = [
//   { label: "2x", value: 2 },
//   { label: "1.5x", value: 1.5 },
//   { label: "1x", value: 1 },
//   { label: "0.75x", value: 0.75 },
// ];

// const onChangeSpeed = (value: number) => {
//   activeSpeed.value = value;
//   audioRef.value.playbackRate = value;
//   speedVisible.value = false;
// };

// const onHandleSpeed = () => {
//   speedVisible.value = !speedVisible.value;
// };

// 设置音量
// const onSetVolume = (value: number) => {
//   audioRef.value.volume = value;
//   audioVolume.value = value;
// };

// // 音频时间格式化换算
// const transTime = (value: number) => {
//   let time = "";
//   let h = parseInt(String(value / 3600));
//   value %= 3600;
//   let m = parseInt(String(value / 60));
//   let s = parseInt(String(value % 60));
//   if (h > 0) {
//     time = formatTime(h + ":" + m + ":" + s);
//   } else {
//     time = formatTime(m + ":" + s);
//   }
//   return time;
// };

// // 格式化时间显示，补零对齐
// const formatTime = (value: string) => {
//   let time = "";
//   let s = value.split(":");
//   let i = 0;
//   for (; i < s.length - 1; i++) {
//     time += s[i].length == 1 ? "0" + s[i] : s[i];
//     time += ":";
//   }
//   time += s[i].length == 1 ? "0" + s[i] : s[i];

//   return time;
// };

// 生命周期
onMounted(async () => {
  try {
    const res = await axios.get("音乐接口");
    // musicSource.value = res.data.music;
    musicSource.value =
      "https://download.588ku.com/audio_library/source/original/24/09/02/05aeb873b8e66f7c258f6d324fee21c4.mp3?key=e65818d9dc133b966a2149ae181b6ef1&t=1743183489&_upd=%E5%8D%83%E5%BA%93%E7%BD%91_%E7%A7%91%E6%8A%80%E5%8A%A8%E6%84%9F%E6%97%B6%E5%B0%9A%E5%88%9B%E6%96%B0%E7%9A%84%E8%8A%82%E5%A5%8F%E7%BA%AF%E9%9F%B3%E4%B9%90_%E9%85%8D%E4%B9%90%E7%BC%96%E5%8F%B7156963.mp3";
    // wenan.value = res.data.singer;
    // sing.value = res.data.name;
    // picture.value = res.data.Picture;
    picture.value =
      "https://p2.music.126.net/X7c0xUfeH3FeGitDVtWDJA==/109951163031611331.jpg?param=300x300";
  } catch (err) {
    error.value = true;
    console.error("加载失败:", err);
  } finally {
    loading.value = false;
  }
});

onBeforeMount(() => {
  clearInterval(timeInterval.value);
});
</script>

<style scoped>
.music-player-container {
  position: fixed;
  width: 100%;
  margin: 2rem auto;
  border-radius: 15px;
  border-radius: 300px;
  position: absolute;
  bottom: 30px;
  margin: 0 auto;
  text-align: center;
  /* border: 1px solid rgba(255, 255, 255, 0.5); */
}

.music-info {
  width: 80px;
  height: 80px;
  background-image: url("@/assets/live/music/cover.png");
  background-position: center center;
  /* 背景图不平铺 */
  background-repeat: no-repeat;
  /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
  /* 让背景图基于容器大小伸缩 */
  background-size: cover;
  display: flex;
  align-items: center;
}

.album-art {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  animation: rotate 20s linear infinite;
  animation-play-state: paused;
  margin-left: 10px;
  img {
    width: 60px;
    height: 60px;
  }
}

.album-art.rotating {
  animation-play-state: running;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.song-details {
  color: white;
  width: 80px;
  line-height: 10px;
  margin-top: 6px;
}

.song-title {
  font-size: 14px;
  line-height: 10px;
}

.artist {
  color: #35bda5;
  font-size: 16px;
}

.audio-player {
  display: flex;
  height: 58px;
  align-items: center;
  gap: 1rem;
  background: #2f2f2f;
  border-radius: 300px;
  padding-right: 20px;
  width: 800px;
  margin: 0 auto;
}

.play-progress {
  cursor: pointer;
  flex-grow: 1;
  height: 4px;
  background-color: #323547;
  box-shadow: inset 0px 1px 0px 0px #20222d;
  border-radius: 2px;
  margin-right: 16px;
  position: relative;
  .play-current-progress {
    height: 4px;
    background: #fff;
    border-radius: 2px;
    position: absolute;
    top: 0;
    left: 0;
  }
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  .el-slider {
    width: 100px;
  }
  .play-voice {
    width: 14px;
    height: 14px;
    cursor: pointer;
  }
  :deep(.el-slider__button) {
    width: 5px;
    height: 10px;
    background: #5ce4ff;
    border-radius: 10px;
    border: 0;
  }
  :deep(.el-slider__button-wrapper) {
    width: 10px;
  }
  :deep(.el-slider__bar) {
    background-color: #5ce4ff;
  }
}

.speed-options {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.speed-option {
  padding: 0.5rem;
  border-radius: 4px;
  transition: all 0.3s;
}

.speed-option:hover,
.speed-option.active {
  background: #35bda5;
  color: white;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 2rem;
}

.play-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}
</style>
